#include "search.h"
#include "ui_search.h"
#include <QUdpSocket>
#include <QTcpSocket>
#include <QHostAddress>
#include <QTimer>
#include <QDebug>
#include <QString>
Search::Search(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Search)
{
    ui->setupUi(this);
    // 创建udp对象
    udpSocket =new QUdpSocket(this);
    // 创建tcp客户端对象
    socket = new QTcpSocket(this);

    // 发送广播槽函数
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(btnSearchSlot()));
    // 接收广播回复
    connect(udpSocket, SIGNAL(readyRead()), this,SLOT(udpRecvSlot()));

    ui->lineEdit->setStyleSheet("background-color: rgba(185, 255, 185, 0.6); border: 1px solid black;");
    ui->textBrowser->setStyleSheet("background-color: rgba(185, 255, 185, 0.6); border: 1px solid black;");
    ui->lcd_time->setDigitCount(8);// 设置 QLCDNumber 的 digitCount 为 8

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout,this,&Search::updateTime);
    timer->start(1000);
    updateTime();
}

Search::~Search()
{
    delete ui;
    //关闭广播
    udpSocket->close();
}

void Search::updateTime()
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentTime = currentDateTime.toString("hh:mm:ss");

    // 将时间显示在一个 QLCDNumber 控件上
        ui->lcd_time->display(currentTime);
}
void Search::on_pushButton_clicked()
{
//    emit searchSignal(ui->lineEdit->text());
    QByteArray datagram = "SEARCH_DEVICE";  // 搜索请求内容
    if(udpSocket == NULL)
    {
        //socket套接字
        udpSocket = new QUdpSocket(this);
        //监控套接字
        connect(udpSocket, &QUdpSocket::readyRead, this, &Search::processPendingDatagrams);
    }
    udpSocket->writeDatagram(datagram, QHostAddress("192.168.0.152"), ui->lineEdit->text().toShort());
}
void Search::processPendingDatagrams()
{
    // 处理接收到的广播数据包
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->bytesAvailable());
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 这里假设设备通过 UDP 响应一个字符串
        QString deviceInfo = QString::fromUtf8(datagram);
        qDebug() << "Received device info from" << sender.toString() << ":" << deviceInfo;

        // 显示设备信息，可以将其显示在界面上
        ui->textBrowser->setText(deviceInfo + "3.IP地址:" + sender.toString());
    }
}

//进行UDP广播
void Search::btnSearchSlot(){
    printf("search button clicked\n");
    // 绑定广播地址192.168.247.228
    QHostAddress broadcastAddress("192.168.247.255");/*ubuntu广播地址*/

    QByteArray datagram = "smart"; // 想要搜索的设备名称
    QByteArray datagram_1;
    if (udpSocket->writeDatagram(datagram, datagram.size(), broadcastAddress, 8888/*port*/)){
        qDebug()<<"广播成功";
        quint16 port=8888;
        QHostAddress sender=QHostAddress("192.168.247.255");

        udpSocket->readDatagram(datagram_1.data(), datagram_1.size(),&sender, &port/*port*/);
        tcpip = sender.toString();//获取服务器地址

        qDebug() << "Received datagram from:" << sender.toString() << datagram.data();
        udpSocket->readDatagram(datagram_1.data(), datagram_1.size(),&sender, &port/*port*/);
        qDebug()<<"收到设备端信息："<<datagram;
    }

    else  qDebug()<<"广播失败";
}

void Search::udpRecvSlot(){
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        tcpip = sender.toString(); // 获取服务器地址
        // 打印发送者地址和接收到的数据
        qDebug() << "Received datagram from:" << sender.toString() << datagram.data();
        if(!strcmp(datagram.data(),"yes"))  ui->textBrowser->append(sender.toString());
        udpSocket->close(); // 关闭广播
    }
}
